import { Modal, Popconfirm, Table } from 'antd'
import { memo, useEffect, useRef } from 'react'
import type { QueryMoneyCardListParams } from '../services'
import { delMoneyCard, queryMoneyCardList } from '../services'
import { useRequest } from 'ahooks'
import dayjs from 'dayjs'

export interface CardListModalProps {
  onCancel?: () => void
  infoId?: number
}

const CardListModal: React.FC<CardListModalProps> = props => {
  const params = useRef<QueryMoneyCardListParams>({
    pageNum: 1, pageSize: 10
  })
  const { data, run, loading, refresh } = useRequest(queryMoneyCardList, {manual: true})
  const { runAsync: delMoneyCardAsync } = useRequest(delMoneyCard, {manual: true})

  const onCancel = () => {
    props.onCancel?.()
  }

  useEffect(() => {
    if (props.infoId) {
      params.current.pageNum = 1
      params.current.infoId = props.infoId
      run(params.current)
    }
  }, [props.infoId])

  return (
    <Modal
      title='卡列表'
      open={!!props.infoId}
      onCancel={onCancel}
      footer={false}
      width={1200}
    >
      <Table
        rowKey='id'
        loading={loading}
        dataSource={data?.data}
        scroll={{x: 'max-content'}}
        pagination={{
          pageSize: params.current.pageSize,
          total: data?.totalCount,
          onChange: (page, pageSize) => {
            params.current.pageNum = page === params.current.pageNum ? 1 : page
            params.current.pageSize = pageSize
            run(params.current)
          }
        }}
        columns={[
          {title: '卡标题', dataIndex: 'title', render: val => val || '--'},
          {title: '兑换码', dataIndex: 'cardCode'},
          {title: '已使用金额(元)', dataIndex: 'cutMoney'},
          {title: '卡面额(元)', dataIndex: 'fullMoney'},
          {title: '截止日期', dataIndex: 'endTime', render: val => val ? dayjs(val).format('YYYY-MM-DD') : '--'},
          {title: '兑换人昵称', dataIndex: 'nickname', render: val => val || '--'},
          {title: '兑换人手机号', dataIndex: 'telephone', render: val => val || '--'},
          {title: '操作', key: 'operation', width: 60, fixed: 'right', render: (_, record) => {
            return record.nickname ? null : <Popconfirm
              title={`确定删除现金卡: ${record.title} 吗?`}
              onConfirm={() => delMoneyCardAsync({id: record.id}).then(refresh)}
              okText="删除"
              cancelText="取消"
            >
              <a>删除</a>
            </Popconfirm>
          }},
        ]}
      />
    </Modal>
  )
}

export default memo(CardListModal)